package com.air.common.filter;


import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


/**
 * 用户登录过滤器
 * @author huangf
 */
public class LoginFilter implements Filter {

    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    protected FilterConfig filterConfig;

    public void init(FilterConfig arg0) throws ServletException {
        filterConfig = arg0;
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        canMap.put("login", "/rest/wx/go");
        canMap.put("wxLogin", "/rest/wx/login");


        if (req.getSession().getAttribute("airUser") == null && !canPass(req.getRequestURI())) {
                HttpServletResponse res = (HttpServletResponse) response;
                String url = req.getRequestURL().toString();
                String f = url.substring(0, url.indexOf(req.getContextPath()));
                String p = f + req.getContextPath() + "/rest/wx/go";
                res.sendRedirect(p);
                return;
        }

        chain.doFilter(request, response);

    }
    // 可以通过的URL集合
    static Map<String, String> canMap = new HashMap<String, String>();

    /**
     * 能否通过
     * @param servletPath
     * @return true:可以通过;false:不能通过
     */
    private boolean canPass(String servletPath) {
        for (Iterator<Entry<String, String>> it = canMap.entrySet().iterator(); it
                .hasNext(); ) {
            Entry<String, String> entry = it.next();
            if (servletPath.indexOf(entry.getValue()) != -1) {
                return true;
            }
        }
        return false;
    }

    public void destroy() {

    }
}
